package com.cws.frame.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cws.enmu.ConfigKey;
import com.cws.enmu.HeaderKey;
import com.cws.enmu.RspCode;
import com.cws.frame.exception.CWSException;
import com.cws.sys.Mem;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;

public class AuthInterceptor implements Interceptor {

	private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

	@Override
	public void intercept(ActionInvocation ai) {

		//log.debug("ws auth interceptor in");
		//log.debug("ws path:" + ai.getViewPath() + ai.getMethodName());

		// 判断鉴权信息
		if (!(ai.getViewPath() + ai.getMethodName()).equals("/auth/login")) {
			// 判断token是否有效
			HttpServletRequest req = ai.getController().getRequest();
			String tokenId = req.getHeader(HeaderKey.X_TokenId.name());
			//log.debug("request tokenId:[" + tokenId + "]");

			if (null == tokenId || tokenId.isEmpty()) {
				throw new CWSException(RspCode.INVALID_TOKENID);
			}

			Long lastTime = Mem.getTokenInfo().get(tokenId);

			if (null == lastTime) {
				throw new CWSException(RspCode.INVALID_TOKENID);
			}

			int tokenInvalidTime = Integer.parseInt(Mem.getConfig().getProperty(ConfigKey.tokenInvalidTime.name()));

			if ((System.currentTimeMillis() - lastTime) < (tokenInvalidTime * 60 * 1000)) {
				// 更新最后一次请求时间
				Mem.resetTokenTime(tokenId, System.currentTimeMillis());
			} else {
				log.info("the token " + tokenId + " has invalid.");
				Mem.removeToken(tokenId);
				throw new CWSException(RspCode.INVALID_TOKENID);
			}

		}

		ai.invoke();

		//log.debug("ws auth interceptor  out");
	}

}
